package com.lh.glorypavilion.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lh.glorypavilion.service.edu.entity.Subject;
import com.lh.glorypavilion.service.edu.entity.excel.ExcelSubjectData;
import com.lh.glorypavilion.service.edu.mapper.SubjectMapper;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@NoArgsConstructor
@AllArgsConstructor
public class ExcelSubjectDataListener extends AnalysisEventListener<ExcelSubjectData> {

    private SubjectMapper subjectMapper;

    /**
     * 遍历每一行数据
     * @param data
     * @param context
     */
    @Override
    public void invoke(ExcelSubjectData data, AnalysisContext context) {
        log.info("读取到一条数据："+data);
        //处理读取出来的数据
        String levelOneTitle = data.getLevelOneTitle();//一级标题
        String levelTwoTitle = data.getLevelTwoTitle();//二级标题
        log.info("一级标题："+levelOneTitle);
        log.info("二级标题："+levelTwoTitle);

        String parentId=null;
        Subject byLevelOneTitle = this.getByLevelOneTitle(levelOneTitle);
        if(byLevelOneTitle==null){
            Subject subject = new Subject();
            subject.setParentId("0");
            subject.setTitle(levelOneTitle);
            //存入数据库
            subjectMapper.insert(subject);
            parentId=subject.getId();
        }else {
            parentId=byLevelOneTitle.getId();
        }
        Subject byLevelTwoTitle = this.getByLevelTwoTitle(levelTwoTitle, parentId);
        if(byLevelTwoTitle==null){
            Subject subject = new Subject();
            subject.setTitle(levelTwoTitle);
            subject.setParentId(parentId);
            subjectMapper.insert(subject);
        }


    }

    /**
     * 所有数据读取之后的收尾工作
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    /**
     * 判断是否存在一级标题
     * @param title
     * @return
     */
    public Subject getByLevelOneTitle(String title){
        QueryWrapper<Subject> subjectQueryWrapper = new QueryWrapper<>();
        subjectQueryWrapper.eq("title",title);
        subjectQueryWrapper.eq("parent_id","0");
        return subjectMapper.selectOne(subjectQueryWrapper);
    }

    /**
     * 判断是否存在一级标题下的二级标题
     * @param title
     * @param parentId
     * @return
     */
    public Subject getByLevelTwoTitle(String title,String parentId){
        QueryWrapper<Subject> subjectQueryWrapper = new QueryWrapper<>();
        subjectQueryWrapper.eq("title",title);
        subjectQueryWrapper.eq("parent_id",parentId);
        return subjectMapper.selectOne(subjectQueryWrapper);
    }
}
